<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <template v-slot:before>
          <span>共{{ page.total }}条记录</span>
        </template>
        <template v-slot:after>
          <el-button
            type="success"
            size="small"
            @click="$router.push('/import')"
            >excel导入</el-button
          >
          <el-button type="danger" size="small" @click="exportData"
            >excel导出</el-button
          >
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="small"
            @click="addEmployee"
            :disabled="!checkPermission('employees')"
            >新增员工</el-button
          >
        </template>
      </page-tools>
      <!-- 放置表格分页 -->
      <el-card>
        <el-table border v-loading="loading" :data="lists">
          <el-table-column type="index" label="序号" sortable="" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="手机号" sortable="" prop="mobile" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="头像" width="120px" align="center">
            <!-- 插槽 -->
            <template slot-scope="{ row }">
              <img
                v-imagerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                alt=""
                style="
                  border-radius: 50%;
                  width: 100px;
                  height: 100px;
                  padding: 10px;
                "
                @click="showQrcode(row.staffPhoto)"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="聘用形式"
            sortable=""
            prop="formOfEmployment"
            :formatter="formatEmployment"
          />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry" />
          <el-table-column
            label="账户状态"
            sortable=""
            prop="formOfEmployment"
            align="center"
          >
            <template v-slot="{ row }">
              <el-switch :value="row ? true : false"> </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
                >查看</el-button
              >
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)"
                >角色</el-button
              >
              <el-button type="text" size="small" @click="delEmployee(row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            layout="prev, pager, next"
            :current-page="page.page"
            :page-size="page.size"
            :total="page.total"
            @current-change="changePge"
          />
        </el-row>
      </el-card>

      <!-- 新增员工弹窗 -->
      <add-employee :show-dialog.sync="showDialog" />
      <el-dialog
        title="二维码"
        :visible.sync="showCodeDiglog"
        @close="showCodeDiglog = false"
      >
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas"></canvas>
        </el-row>
      </el-dialog>
      <!-- 角色弹窗  .sync修饰符可以直接在子组件更新父组件的值-->
      <assign-role
        :showRoleDialog.sync="showRoleDialog"
        :userId="userId"
        ref="assignRole"
      />
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from "@/api/employees";
import EmployeeEnum from "@/api/constant/employees";
import addEmployee from "./components/add-employee.vue";
import { formatDate } from "@/utils/filters";
import QrCode from "qrcode";
import assignRole from "./components/assign-role.vue";
export default {
  components: {
    addEmployee,
    assignRole,
  },
  data() {
    return {
      EmployeeEnum,
      lists: [],
      loading: false,
      page: {
        page: 1,
        size: 10,
        total: 0,
      },
      showDialog: false, //新增弹层
      showCodeDiglog: false, //展示二维码弹层
      showRoleDialog: false,
      userId: null,
    };
  },
  created() {
    this.getEmployeeList();
  },
  methods: {
    async getEmployeeList() {
      this.loading = true;
      const { total, rows } = await getEmployeeList(this.page);
      this.lists = rows;
      this.page.total = total;
      this.loading = false;
    },
    changePge(newPage) {
      this.page.page = newPage; //赋值最新的页码
      this.getEmployeeList(); //重新获取数据
    },
    //格式化聘用形式
    formatEmployment(row, column, cellValue, index) {
      const list = EmployeeEnum.hireType; //获取枚举数组
      const obj = list.find((item) => item.id === cellValue);
      return obj ? obj.value : "未知";
    },
    //删除员工
    async delEmployee(id) {
      try {
        await this.$confirm("确定删除员工吗？");
        await delEmployee(id);
        thsi.getEmployeeList();
        this.$message.success("操作成功");
      } catch (err) {
        console.log(err);
      }
    },
    //新增员工
    addEmployee() {
      this.showDialog = true;
    },
    //导出数据
    exportData() {
      // 表头对应关系
      const headers = {
        姓名: "username",
        手机号: "mobile",
        入职日期: "timeOfEntry",
        聘用形式: "formOfEmployment",
        转正日期: "correctionTime",
        工号: "workNumber",
        部门: "departmentName",
      };
      import("@/vendor/Export2Excel").then(async (excel) => {
        const { rows } = await getEmployeeList({
          page: 1,
          size: this.page.total,
        });
        const data = this.format(headers, rows);
        //导出表格方法
        const tHeader = Object.keys(headers);
        excel.export_json_to_excel({
          header: tHeader, //表头 必填
          data, //具体数据 必填
          filename: "excel-list", //非必填
          autoWidth: true, //非必填
          bookType: "xlsx", //非必填
        });
      });
    },
    // 该方法负责将数组转化成二维数组
    format(headers, rows) {
      // 首先遍历数组
      // [{ username: '张三'},{},{}]  => [[’张三'],[],[]]
      var ooArr = rows.map((item) => {
        var arr = Object.keys(headers).map((key) => {
          //这层return的是数组
          if (
            headers[key] === "timeOfEntry" ||
            headers[key] === "correctionTime"
          ) {
            return formatDate(item[headers[key]]); // 返回格式化之前的时间
          } else if (headers[key] === "formOfEmployment") {
            var en = EmployeeEnum.hireType.find(
              (obj) => obj.id === item[headers[key]]
            );
            return en ? en.value : "未知";
          }
          return item[headers[key]];
        }); // => ["张三", "13811"，"2018","1", "2018", "10002"]
        // console.log("arr", arr);
        return arr;
      });
      // console.log("arr", ooArr);
      return ooArr;
    },
    //点击图片显示二维码
    showQrcode(imgSrc) {
      if (imgSrc) {
        this.showCodeDiglog = true;
        //有一个方法可以在上一次数据更新完毕，页面渲染完毕之后
        this.$nextTick(() => {
          QrCode.toCanvas(this.$refs.myCanvas, imgSrc);
        });
      } else {
        this.$message.warning("该用户还未上传头像");
      }
    },
    //点击角色
    async editRole(userId) {
      this.userId = userId;
      await this.$refs.assignRole.getUserDetailById(userId);
      this.showRoleDialog = true;
    },
  },
};
</script>

<style>
</style>
